import { Component } from 'react';
import Taro from '@tarojs/taro';
import { ScrollView, View, Image, Text} from '@tarojs/components'
import { AtMessage } from 'taro-ui'
import Iconfont from '@/components/Iconfont'
import CarInfo from '@/components/CarInfo'
import { connect } from 'react-redux'
import classnames from 'classnames'
import './index.scss'
import { upDatedDiyCategory } from '@/store/annual/action'
import { delayQuerySelector, accAdd, accSub,throttle } from '@/utils'
import { getDiyListByCarId } from '@/api/annual'
import qs from 'qs'
type State = {
	isFix: boolean
	navIndex: number
	scrollTop: number
	diyList: Array<any>
	form: any
	disabledSubmit: boolean
	totalPrice: any
}
@connect<any>(({ annual, car }) => ({ annual, car }), _dispatch => ({
  dispatchDiyList(data) {
    return _dispatch(upDatedDiyCategory(data))
  }
}))

export default class AnnualDiyIndex extends Component<any, State> {
	protected bannerH: number
	protected bannerImg: string = `${SOURCES_PATH}/img/annual/banner.png`
	protected cartImg: string = `${SOURCES_PATH}/img/annual/cart.png`
	protected jekunModelCode: string
	protected minPrice: number
	constructor(props) {
		super(props)
		this.state = {
			isFix: false,
			navIndex: 0,
			scrollTop: 0,
			diyList: [],
			disabledSubmit: true,
			form: {
				items: 2
			},
			totalPrice: {
				goodsPrice: '--',
				originGoodsPrice: '--',
				remainAmount: '--'
			}
		}
	}
	static options = {
    addGlobalClass: true
  }

	handleClick(item) {
		Taro.navigateTo({
			url: `/pages/detection/detail/index?reportId=${item.reportId}&title=${item.typeLabel}`
		})
	}
	onScroll(e) {
	}

	handleChangeNavIndx(index: number) {
			let { isFix } = this.state
			if (isFix) {
				this.setState({
					scrollTop: 0
				}, () => {
						this.setState({
							scrollTop: this.bannerH
						})
				})
			}
			this.setState({
				navIndex: index
			})

		//}
	}
	UNSAFE_componentWillMount() {
		delayQuerySelector(this, '.banner-wrap', 0).then(rect => {
			if (rect[0]) {
				this.bannerH = rect[0].height
			}
		})
	}

	async componentDidMount() {
		if (this.props.car.carInfo.currentCar) {
			this.jekunModelCode = this.props.car.carInfo.currentCar.jekunModelCode
			Promise.all([this.getDiyListByCarId(this.jekunModelCode)])
		}
	}

	UNSAFE_componentWillReceiveProps(nextProps) {
		let { diyList } = this.state
		let data = [...diyList]

		if (nextProps.car.carInfo.currentCar && this.jekunModelCode !== nextProps.car.carInfo.currentCar.jekunModelCode) {
			this.jekunModelCode = nextProps.car.carInfo.currentCar.jekunModelCode
			Promise.all([this.getDiyListByCarId(this.jekunModelCode)])
			return
		}
		if (nextProps.annual.categoryItem) {
			let categoryItem = nextProps.annual.categoryItem
			let eachBuy = data[categoryItem.parentKey].eachBuy
			let grandfatherKey = categoryItem.parentKey
			let categoryKey = categoryItem.categoryKey
			let carModelMatchType = data[grandfatherKey].items[categoryKey].carModelMatchType
			let goodsItems = categoryItem.goodsItems.map((i, index) => {
				return {
					...i,
					num: Number(i.num) !== 0 ? eachBuy * Number(i.num) : i.num,
					baseNum: Number(i.num),
					grandfatherKey,
					categoryKey,
					goodsKey: index
				}
			})
			categoryItem.goodsItems = goodsItems
			categoryItem.carModelMatchType = carModelMatchType
			data[grandfatherKey].items[categoryKey] = categoryItem
			this.setState({
				diyList: this.setTotalLaborFeeAndCounts(data)
			}, () => {
				this.calcTotalPrice()
			})
		}
	}

	async getDiyListByCarId(jekunModelCode) {
		Taro.showLoading({
			title: '加载中'
		})
		try {
			let res = await getDiyListByCarId({
				query: {
					filter: {
						and: [{
							id: 9
						}]
					},
					page: 1
				},
				jekunModelCode
			})
			let {goodsList,minPrice} =  res.data.data
			this.minPrice = +minPrice
			let data = this.forMatData(goodsList)
			this.setState({
				diyList: this.setTotalLaborFeeAndCounts(data)
			}, () => {
				this.calcTotalPrice()
			})
		} catch (error) {

		} finally {
			Taro.hideLoading()
		}

	}


	forMatData(data) {
		let eachBuy = 1
		let newArr = data.map((i, index) => {
			return {
				...i,
				totalLaborFee: 0,
				key: index,
				eachBuy,
				items: forMatItem(i.items, index, eachBuy)
			}
		})
		function forMatItem(arr: Array<any>, key: number, eachBuy: number): Array<any> {
			arr = arr.map((i, index) => {
				return {
					...i,
					parentKey: key,
					categoryKey: index,
					goodsItems: forMatGoodsItem(i.goodsItems, key, index, eachBuy)
				}
			})
			return arr
		}
		function forMatGoodsItem(arr: Array<any>, grandfatherKey: number, categoryKey: number, eachBuy: number): Array<any> {
			arr = arr.map((i, index) => {
				return {
					...i,
					num: Number(i.num) !== 0 ? eachBuy * Number(i.num) : i.num,
					baseNum: Number(i.num) !== 0 ? eachBuy * Number(i.num) : i.num,
					grandfatherKey,
					categoryKey,
					goodsKey: index
				}
			})
			return arr
		}
		return newArr
	}
	setTotalLaborFeeAndCounts(arr: Array<any>): Array<any> {

		arr = arr.map(i => {
			return {
				...i,
				totalLaborFee: this.calcItemTotalLaborFee(i.items)
			}
		})
		return arr
	}

	calcItemTotalLaborFee(arr: Array<any>): number {
		let total = 0
		arr.map(i => {
			if (Number(i.laborFee) !== 0) {
				total +=  Number(i.laborFee)
			}
		})
		return total
	}

	calcGoodsItemNum(arr: Array<any>, eachBuy: number | string): Array<any> {
		let newArr: Array<any> = []
		arr.map(i => {
			newArr.push({
				...i,
				num: Number(eachBuy) * Number(i.baseNum)
			})
		})
		return newArr
	}

	calcTotalPrice() {
		let { diyList } = this.state
		let [goodsPrice, originGoodsPrice, remainAmount, allTotalLaborFee] = [0, 0, 0, 0]

		for (let i in diyList) {
			let items = diyList[i].items
			allTotalLaborFee += Number(diyList[i].totalLaborFee) * Number(diyList[i].eachBuy)
			for (let j in items) {
				let goodsItems = items[j].goodsItems
				for (let k in goodsItems) {
					goodsPrice += Number(goodsItems[k].goods.annualCardPrice) * Number(goodsItems[k].num)
					originGoodsPrice += Number(goodsItems[k].goods.platformPrice) * Number(goodsItems[k].num)
				}
			}
		}
		remainAmount = Number(accSub(accAdd(goodsPrice, allTotalLaborFee), this.minPrice))
		this.setState({
			totalPrice: {
				goodsPrice: accAdd(goodsPrice, allTotalLaborFee),
				originGoodsPrice: accAdd(originGoodsPrice, allTotalLaborFee),
				remainAmount
			},
			disabledSubmit: remainAmount < 0
		})
	}

	handleAddCount(index) {
		let { diyList } = this.state
		let item = diyList[index]
		item.eachBuy ++
		if (item.maxBuy && item.eachBuy > item.maxBuy) {
			Taro.showToast({
				title: `最大购买为${item.maxBuy}哦～`,
				icon: 'none'
			})
			// 还原次数
			item.eachBuy --
			return
		}
		Taro.vibrateShort()
		this._updateDisList(index, item)
	}

	handleReduceCount(index) {
		let { diyList } = this.state
		let item = diyList[index]
		if (item.eachBuy <= 0) return
		item.eachBuy --

		if (+item.isMustBuy === 1) {
			if (item.eachBuy < 1) {
				Taro.showToast({
					title: '最小购买为1哦～',
					icon: 'none'
				})
				// 还原次数
				item.eachBuy = 1
				return
			}
		}

		Taro.vibrateShort()
		this._updateDisList(index, item)
	}
	_updateDisList = throttle((index, item) => {
		let { diyList } = this.state
		let data = [...diyList]
		let newItem = data[index]
		newItem.eachBuy  = item.eachBuy
		newItem.totalLaborFee = this.calcItemTotalLaborFee(item.items)
		newItem.items = newItem.items.map(i => {
			return {
				...i,
				goodsItems: this.calcGoodsItemNum(i.goodsItems, item.eachBuy)
			}
		})
		data[item.key] = item
		this.setState({
			diyList: data
		}, () => {
			this.calcTotalPrice()
		})
	}, 200)

	handleToSelectSpec(category) {
		Taro.navigateTo({
			url: `/pages/annual/diySpec/index?${qs.stringify({
				jekunModelCode: this.props.car.carInfo.currentCar.jekunModelCode,
				categoryCode: category.categoryCode,
				carModelMatchType: category.carModelMatchType,
				categoryKey: category.categoryKey,
				parentKey: category.parentKey,
			})}`
		})
	}

	handleSubmit() {
		let { diyList, disabledSubmit } = this.state
		if (!disabledSubmit) {
			const diyAnnual: any = {
				annualCardType: 2,
				annualCardId: 0,
				annualCardName: '',
				totalLaborFee: 0,
				price: 0,
				items: []
			}
			diyList.forEach(list => {
				diyAnnual.totalLaborFee += Number(list.totalLaborFee) * list.eachBuy
				list.items.forEach(function(item) {
					const relatedNum = item.categoryCode
					const laborFee = Number(item.laborFee)
					item.goodsItems.forEach(v => {
						const { goodsId, annualCardPrice, goodsName, thumbnailUrl, tags } = v.goods
						diyAnnual.price += Number(annualCardPrice) * Number(v.num)
						if (+list.eachBuy > 0) {
							diyAnnual.items.push({
								goodsId: Number(goodsId),
								goodsName,
								thumbnailUrl,
								annualCardPrice,
								type: laborFee > 0 ? 1 : 0,
								eachUse: v.baseNum,
								relatedNum,
								tags,
								buyNum: list.eachBuy
							})
						}
					})
				})
			})
			diyAnnual.annualCardName = `${diyAnnual.price}元DIY年卡`
			Taro.navigateTo({
				url: `/pages/order/index/index?type=1&diyAnnual=${JSON.stringify(diyAnnual)}`
			})
		}
	}

	render() {
		const scrollStyle = {
			height: '100vh'
		}
		let { diyList, scrollTop, disabledSubmit, totalPrice } = this.state
		return (
			<View className='annual-diy-wrap'>
				<View className='car-info'>
					<CarInfo />
				</View>
				<View className='cart-wrap'>
					<View className='cart'>
						<View className='left'>
							<View className='count'>
								<View>¥<Text className='total'>{totalPrice.goodsPrice}</Text><Text className='origin-total'>￥{totalPrice.originGoodsPrice}</Text></View>
								<View className='tip'>
									<Text>最低消费￥{this.minPrice}</Text>
									{ totalPrice.remainAmount < 0 && <Text> | 还差￥{Math.abs(totalPrice.remainAmount)}</Text> }
								</View>
							</View>
						</View>
						<View className={classnames('btn', {
							'disabled': disabledSubmit
						})} onTouchStart={this.handleSubmit.bind(this)}
						>
							去结算
						</View>
					</View>
				</View>
				<ScrollView className='list' scrollWithAnimation enableBackToTop scrollTop={scrollTop} scrollY onScroll={this.onScroll.bind(this)} style={scrollStyle}>
					<View className='content-wrap'>
						{ diyList.map((item, index) =>
							<View className='content-wrap-item' key={Number(item.id)}>
								<View className='content-wrap-item-head'>
									<View className='left'>
										<Text className='title'>{item.name}</Text>
										<Text className='desc'>{item.circle}</Text>
									</View>
									<View className='right'>
										<Text className='desc'>购买次数</Text>
										<View className='input-num'>
											<View className='down number-action' onTouchStart={this.handleReduceCount.bind(this, index)}>
												{
													((item.isMustBuy === 1 && item.eachBuy > 1) || (item.isMustBuy === 0 && item.eachBuy > 0)) &&
													<Iconfont size='24' color='#333' name='icon-jian-gaoliang' /> }
												{
													((item.isMustBuy === 1 && item.eachBuy === 1) || (item.isMustBuy === 0 && item.eachBuy === 0)) &&
													<Iconfont size='24' color='#eee' name='icon-jian-gaoliang' />
												}
											</View>
											<View  className='number'>{item.eachBuy}</View>
											<View className='up number-action' onTouchStart={this.handleAddCount.bind(this, index)}>
												{
													(!item.maxBuy || item.maxBuy && Number(item.eachBuy) !== Number(item.maxBuy)) &&
													<Iconfont size='24' color='#fff' name='icon-jia-gaoliang' />
												}
												{
													item.maxBuy > 0 && item.eachBuy === item.maxBuy &&
													<Iconfont size='24' color='#eee' name='icon-jia-gaoliang' />
												}
											</View>
											<View></View>
										</View>
									</View>
								</View>
								{
									item.tip && <View className='content-tips'>{item.tip}</View>
								}
								{ item.eachBuy > 0 && item.items.map((category, categoryIndex) =>
									<View className='content-wrap-item-content' key={'category' + categoryIndex}>
										{ category.goodsItems.map((goods) =>
											<View className='item-info' key={goods.goodsId}>
												<View className='left'>
													<Image className='annual-img' mode='aspectFill' src={goods.goods.thumbnailUrl}></Image>
												</View>
												<View className='right'>
													<Text className='goods-name'>{ goods.goods.goodsName }</Text>
													<View className='r-bottom-wrap'>
															<View className='r-bottom-t'>
																{ goods.goods.tags && goods.goods.tags.length>0 && <View className='tag'>{goods.goods.tags.join(',')}</View>}
																<Text>已售出{goods.goods.saleCount}件</Text>
															</View>
														{/* </View> */}
														<View className='r-bottom-b'>
															<View className='r-bottom-b-r'>
																￥<Text className='price'>{Number(goods.goods.annualCardPrice)}</Text>
															<Text className='origin-price'>￥{ goods.goods.platformPrice }</Text>
															</View>
															{ category.mark === 1 && <View className='btn-wrap' onTouchStart={this.handleToSelectSpec.bind(this, category)}>
																	<View className='btn'>选规格</View>
																	<View className='dotted'>{goods.num}</View>
																</View>
															}
															{
																category.mark === 0 && <Text className='count'>x {goods.num}</Text>
															}
														</View>
													</View>
												</View>
											</View>
										)}
									</View>
								)}
								{ this.state.diyList[index].eachBuy > 0 && item.totalLaborFee ? <View className='content-wrap-item-bottom'>
										<View className='content-wrap-item-bottom-left'>
											<View>
												<View></View>
												<Text>工时费：</Text>
											</View>
											<Text className='wage'>￥{item.totalLaborFee}</Text>
										</View>
										<Text className='content-wrap-item-bottom-right'>x {this.state.diyList[index].eachBuy}</Text>
									</View> : null
								}
							</View>
						)}
					</View>
				</ScrollView>
				<AtMessage />
				{
					diyList.length == 0 && 	<View className='tips-loading'>
					正在加载中...
				</View>
				}

			</View>
		)
	}
}
